package com.api.customization.fenbeitong;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.yunzhou.utils.DBTools;
import com.yunzhou.utils.DateTools;
import com.yunzhou.utils.HttpClientUtils;
import com.yunzhou.utils.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Date 2022-09-05
 * @Version 1.0
 * @Description TODO 同步分贝通token 获取单点登录地址
 **/
@Path("fenbeitong")
public class AccessTokenApi extends BaseBean{
    private LogTool logTool = new LogTool("/log/fenbeitong/AccessTokenApi", false);

    private final HttpClientUtils client = new HttpClientUtils();
    private final DateTools dateTools = new DateTools();
    private final DBTools dbTools = new DBTools();

    /**
     * 同步access_token
     * @return
     */
    public Map<String,Object> getAppInfo(){
        Map<String,Object> result = new HashMap<>();
        result.put("status",true);
        result.put("msg","");
        RecordSetTrans rst = new RecordSetTrans();
        RecordSet rs = new RecordSet();
        rs.execute("select top 1 * from uf_fenbeitong");
        String date = dateTools.getCurrentDate(),time = dateTools.getCurrentTime();
        if(rs.next()){
            String app_url = rs.getString("app_url"),path_url = rs.getString("path_url"),
                    app_id = rs.getString("app_id"),app_key = rs.getString("app_key"),
                    sign_key = rs.getString("sign_key"),access_token = rs.getString("access_token"),
                    lastmoddate = rs.getString("lastmoddate"),lastmodtime = rs.getString("lastmodtime");
            result.put("app_url",app_url);
            result.put("path_url",path_url);
            result.put("app_id",app_id);
            result.put("app_key",app_key);
            result.put("sign_key",sign_key);
            result.put("access_token",access_token);
            result.put("lastmoddate",lastmoddate);
            result.put("lastmodtime",lastmodtime);
            //保证关键信息都存在
            if(path_url.isEmpty() || app_url.isEmpty()
                    || app_id.isEmpty() || app_key.isEmpty() || sign_key.isEmpty()){
                result.put("status",false);
                result.put("msg","查询表uf_fenbeitong存在未维护的信息");
                return result;
            }
            //构建参数
            Map<String, String> params = new HashMap<>();
            params.put("app_id", app_id);
            params.put("app_key", app_key);

            if(access_token.isEmpty()){
                try {
                    JSONObject infos = JSONObject.parseObject(client.post(app_url+"/open/api/auth/v1/dispense", params));
                    logTool.writeLog(JSONObject.toJSONString(infos));
                    if(infos==null || !infos.getString("code").equals("0")){
                        result.put("status",false);
                        result.put("msg",infos.get("msg"));
                    }
                    String token =infos.getJSONObject("data").getString("access_token");
                    boolean up = rst.executeUpdate("update uf_fenbeitong set access_token=?,lastmoddate=?,lastmodtime=?", token,date,time);
                    if(up){
                        result.put("access_token",token);
                        result.put("lastmoddate",date);
                        result.put("lastmodtime",time);
                    }else{
                        result.put("status",false);
                        result.put("msg","插入access_token失败");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",false);
                    result.put("msg","插入access_token失败,程序异常 "+e.getMessage());
                }
            }else{
                //如果数据都存在则判断token的时效性 根据lastmoddate与当前日期判断
                try {
                    Date dt1 = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date dt2 = format.parse(lastmoddate);
                    Integer between_days = Integer.parseInt(
                            String.valueOf((dt1.getTime() - dt2.getTime())/(1000*3600*24))
                    );
                    //token超过8天重新获取
                    if(between_days>=8){
                        JSONObject infos = JSONObject.parseObject(client.post(app_url+"/open/api/auth/v1/dispense", params));
                        logTool.writeLog(JSONObject.toJSONString(infos));
                        if(infos==null || !infos.getString("code").equals("0")){
                            result.put("status",false);
                            result.put("msg",infos.get("msg"));
                        }
                        String token = infos.getJSONObject("data").getString("access_token");
                        boolean up = rst.executeUpdate("update uf_fenbeitong set access_token=?,lastmoddate=?,lastmodtime=?", token,date,time);
                        if(up){
                            result.put("access_token",token);
                            result.put("lastmoddate",date);
                            result.put("lastmodtime",time);
                        }else{
                            result.put("status",false);
                            result.put("msg","更新access_token失败,执行update异常");
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",false);
                    result.put("msg","更新access_token失败,程序异常 "+e.getMessage());
                }
            }
        }else{
            result.put("status",false);
            result.put("msg","未查询到表uf_fenbeitong存在数据");
        }
        return result;
    }

    //获取access_token有关信息
    @GET
    @Path("/getAppinfo")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> getToken(@Context HttpServletRequest request,
                                        @Context HttpServletResponse response) {
        return getAppInfo();
    }

    //获取登录token
    @GET
    @Path("/getPathToken")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> getPathToken(@Context HttpServletRequest request,
                                            @Context HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        result.put("status",true);
        result.put("msg","");

        Map<String, Object> requestParams = ParamUtil.request2Map(request);

        Map<String, Object> appInfo = new HashMap<>();
        try{
            appInfo = getAppInfo();
            if(!(boolean)appInfo.get("status")){
                result.put("status",false);
                result.put("msg","getAppInfo error "+appInfo.get("code"));
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",false);
            result.put("msg","getAppInfo error  "+e.getMessage());
            return result;
        }
        User user = HrmUserVarify.getUser(request, response);//获取当前用户
        try {
            String app_url = (String) appInfo.get("app_url");
            String path_url = (String) appInfo.get("path_url");
            String app_id = (String) appInfo.get("app_id");
            String app_key = (String) appInfo.get("app_key");
            //构建参数
            Map<String, String> params = new HashMap<>();
            params.put("tp_mobile", user.getMobile());
            params.put("app_id", app_id);
            params.put("app_key", app_key);
            //获取单点登录有关token
            JSONObject infos = JSONObject.parseObject(client.ajaxPostJson(app_url+"/open/web/auth/v1/dispense", JSONObject.toJSONString(params)));
            logTool.writeLog(JSONObject.toJSONString(infos));
            if(infos==null || !infos.getString("code").equals("0")){
                result.put("status",false);
                result.put("msg",infos.get("msg"));
                return result;
            }
            String token =infos.getJSONObject("data").getString("token");
            result.put("token",token);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",false);
            result.put("msg","获取单点登录token异常 "+e.getMessage());
        }
        return result;
    }
    //单点登录-WebApp嵌入
    @GET
    @Path("/getPathTokenV2")
    @Produces(MediaType.APPLICATION_JSON)
    public void getPathTokenV2(@Context HttpServletRequest request,
                               @Context HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        result.put("status",true);
        result.put("msg","");
        Map<String, Object> requestParams = ParamUtil.request2Map(request);
//        PrintWriter writer = response.getWriter();
        if(!requestParams.containsKey("path")){
            result.put("status",false);
            result.put("msg","未获取到接口参数[path]");
            logTool.writeLog(JSONObject.toJSONString(result));
//            response.setContentType("text/html; charset=utf-8");
//            writer.write(JSONObject.toJSONString(result));
            response.sendRedirect("/tokenError.html");
            return ;
        }
        String path = (String) requestParams.get("path");
        if(path.isEmpty()){
            result.put("status",false);
            result.put("msg","接口参数[path]为空");
            logTool.writeLog(JSONObject.toJSONString(result));
//            response.setContentType("text/html; charset=utf-8");
//            writer.write(JSONObject.toJSONString(result));
            response.sendRedirect("/tokenError.html");
            return ;
        }

        Map<String, Object> appInfo = new HashMap<>();
        try{
            appInfo = getAppInfo();
            if(!(boolean)appInfo.get("status")){
                result.put("status",false);
                result.put("msg","getAppInfo error "+appInfo.get("code"));
                logTool.writeLog(JSONObject.toJSONString(result));
//                response.setContentType("text/html; charset=utf-8");
//                writer.write(JSONObject.toJSONString(result));
                response.sendRedirect("/tokenError.html");
                return ;
            }
        }catch (Exception e){
            result.put("status",false);
            result.put("msg","getAppInfo error  "+e.getMessage());
            logTool.writeLog(JSONObject.toJSONString(result));
//            response.setContentType("text/html; charset=utf-8");
//            writer.write(JSONObject.toJSONString(result));
            response.sendRedirect("/tokenError.html");
            return ;
        }
        User user = HrmUserVarify.getUser(request, response);//获取当前用户
        try {
            String app_url = (String) appInfo.get("app_url");
            String path_url = (String) appInfo.get("path_url");
            String app_id = (String) appInfo.get("app_id");
            String app_key = (String) appInfo.get("app_key");
            //构建参数
            Map<String, String> params = new HashMap<>();
            params.put("tp_mobile", user.getMobile());
            params.put("app_id", app_id);
            params.put("app_key", app_key);
            //获取单点登录有关token
            JSONObject infos = JSONObject.parseObject(client.ajaxPostJson(app_url+"/open/web/auth/v1/dispense", JSONObject.toJSONString(params)));
            if(infos==null || !infos.getString("code").equals("0")){
                result.put("status",false);
                result.put("msg",infos.get("msg"));
                logTool.writeLog(JSONObject.toJSONString(result));
//                response.setContentType("text/html; charset=utf-8");
//                writer.write(JSONObject.toJSONString(result));
                response.sendRedirect("/tokenError.html");
                return ;
            }
            String token =infos.getJSONObject("data").getString("token");
            result.put("token",token);
            result.put("url",path_url+"?token="+token+"&path="+path);
            logTool.writeLog(JSONObject.toJSONString(result));
            response.sendRedirect(path_url+"?token="+token+"&path="+path);
            return ;
        }catch (Exception e){
            result.put("status",false);
            result.put("msg","获取单点登录token异常 "+e.getMessage());
            logTool.writeLog(JSONObject.toJSONString(result));
//            response.setContentType("text/html; charset=utf-8");
//            writer.write(JSONObject.toJSONString(result));
            response.sendRedirect("/tokenError.html");
            return ;
        }
    }

    //单独提供自定义部门矩阵的查询接口
    @GET
    @Path("/getMatrixInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> getMatrixInfo(@Context HttpServletRequest request,
                                        @Context HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        result.put("status",0);
        result.put("msg","");
        Map<String, Object> requestParams = ParamUtil.request2Map(request);
        if(!requestParams.containsKey("matrixid")){
            result.put("status",1);
            result.put("msg","未获取到接口参数[matrixid]");
            return result;
        }
        String matrixid = (String) requestParams.get("matrixid");
        if(matrixid.isEmpty()){
            result.put("status",1);
            result.put("msg","接口参数[matrixid]为空");
            return result;
        }
        List<Map<String,String>> datas = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.execute("select * from matrixtable_"+matrixid);
        String[] cloumns = rs.getColumnName();
        while (rs.next()){
            Map<String,String> data = new HashMap<>();
            for(int i=0;i<cloumns.length;i++){
                data.put(cloumns[i].toLowerCase(),rs.getString(cloumns[i]));
            }
            datas.add(data);
        }
        result.put("datas",datas);
        return result;
    }

}
